﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PersonaLibrary.Data.Help
{
    public static class DataContextHelper
    {
        public static void ResetAllChanges( Data.LinqToDbDataContext context )
        {
            foreach (var item in context.GetChangeSet().Inserts)
                context.GetTable(item.GetType()).DeleteOnSubmit(item);

            foreach (var item in context.GetChangeSet().Deletes)
                context.GetTable(item.GetType()).InsertOnSubmit(item);

            context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, context.GetChangeSet().Updates);
        }

        public static void SaveItem<TEntity>(TEntity item)
            where TEntity : BaseEntity
        {
            if (item.Id == 0)
            {
                using (var context = new LinqToDbDataContext())
                {
                    context.GetTable<TEntity>().InsertOnSubmit(item);
                    context.SubmitChanges();
                }
            }
            else
            {
                TEntity original;
                using (var context = new LinqToDbDataContext())
                {
                    original = context.GetTable<TEntity>().Single(x => ((TEntity) x).Id == item.Id);
                }

                using (var context = new LinqToDbDataContext())
                {
                    context.GetTable<TEntity>().Attach(item, original);
                    context.SubmitChanges();
                }
            }
        }
    }
}
